<template>
  <div v-loading="loading">
    <div class="qup-page-heade bread-box">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item class="btn-green" @click.native="goBack">楼盘签约管理</el-breadcrumb-item>
        <el-breadcrumb-item>楼盘签约信息</el-breadcrumb-item>
      </el-breadcrumb>
      <div>
        <el-button size="mini" @click.native="goBack">返回</el-button>
      </div>
    </div>
    <section>
      <el-form
        ref="refForm"
        style="margin-top:20px"
        :model="formData"
        :rules="rules"
        size="mini"
        label-width="150px"
      >
        <el-row>
          <el-col v-if="flag!=='new'" :span="8">
            <el-form-item label="楼盘签约编码:" prop="realEstateContractNumber">
              {{ formData.realEstateContractNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="小区名称:" prop="communityName">
              <el-input v-model="formData.communityName" :disabled="readonly" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="小区详细地址:" prop="communityAddress">
              <el-input v-model="formData.communityAddress" :disabled="readonly" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="交房日期:" prop="houseDeliveryTime">
              <el-date-picker
                v-model="formData.houseDeliveryTime"
                :disabled="readonly"
                style="width: 100%"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="楼盘装修类型:" prop="roomDecorateType">
              <el-select
                v-model="formData.roomDecorateType"
                :disabled="readonly"
                style="width: 100%"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in decorateTypeList"
                  :key="item.dictId"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="提报月份:" prop="submissionDate">
              <el-date-picker
                v-model="formData.submissionDate"
                :disabled="readonly"
                style="width: 100%"
                type="month"
                value-format="yyyy-MM"
                placeholder="选择月"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="0">
          <el-col :span="8">
            <el-form-item label="交房户数:" prop="deliveryModelRoomNumber">
              <el-input v-model.number="formData.deliveryModelRoomNumber" :disabled="readonly" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户:" prop="customerItem">
              <span v-if="flag!=='new'">{{ formData.customerCode }}</span>
              <input-with-dialog
                v-else
                ref="cliDialog"
                v-model="formData.customerItem"
                :props="{label:'code',value:'code'}"
                :config="clientConfig"
                @change="clientChoose"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称:" prop="customerName">
              {{ formData.customerName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属办事处:" prop="agencyName">
              {{ formData.agencyName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="办事处性质:" prop="agencyNature">
              {{ agencyNature }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="成品客户经理:" prop="finishedProductCustomerManagerItem">
              <Submitter
                :disabled="!formData.customerCode||readonly"
                :default-val="formData.finishedProductCustomerManagerName"
                :customer-code="formData.customerCode"
                @choose="finishedCustomerChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="定制客户经理:" prop="customCustomerManagerName">
              <Submitter
                :disabled="!formData.customerCode||readonly"
                :default-val="formData.customCustomerManagerName"
                :customer-code="formData.customerCode"
                @choose="customCustomerChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="市场级别:" prop="marketLevel">
              {{ marketLevel }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数据来源:" prop="dataSource">
              {{ formData.dataSource===1?'手工新增':'BPM' }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否建设样板间:" prop="isBuildModelRoom">
              {{ isBuildModelRoom }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="启用状态:" prop="enable">
              {{ formData.enable===1?'启用':'禁用' }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="提报人:" prop="submitterName">
              <Submitter
                :disabled="readonly"
                flag="0"
                :default-val="formData.submitterName"
                @choose="chooseCons"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建人:" prop="taskSourceDesc">
              {{ formData.createBy||this.$store.getters.user.data.userName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间:" prop="taskSourceDesc">
              {{ formData.createTime||nowTime() }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="0">
          <el-col :span="12">
            <el-form-item label="附件信息:" prop="accessory">
              <p class="file-p">
                <fileUploader
                  ref="myUploader"
                  :data="dataFileList"
                  :limit="1"
                  :show-download-temp="false"
                  :show-edit="false"
                  :show-remove="!readonly"
                  :show-upload="!readonly"
                  @remove="removeFile"
                  @upload-success="uploadSuccessFile"
                />
              </p>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!readonly" :gutter="0">
          <el-col :span="24" style="text-align:center;">
            <el-button type="default" @click="goBack">取消</el-button>
            <el-button type="primary" :loading="loading" @click="confirm">确认</el-button>
          </el-col>
        </el-row>
      </el-form>
    </section>
    <el-image-viewer
      v-if="showViewer"
      :on-close="closeViewer"
      :url-list="urlList"
    />
  </div>
</template>
<script>
import { getDictByPatchType } from '@/api/dataDict'
import { signingRealEstate, getSigningRealEstateCustomer } from '@/api/channelTaskMng'
import { nowTime } from '@/utils/tool'
import fileUploader from '@/components/importFile/FileUploader'
import BackPageMixin from '@/mixins/backPage'
export default {
  name: 'DetailChannelTask',
  components: {
    Submitter: () => import('../components/SubmitterDialog'),
    fileUploader
  },
  mixins: [BackPageMixin],
  props: {
    flag: {
      type: String,
      default() {
        return 'new'
      }
    },
    row: {
      type: [Object, Array],
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      nowTime,
      showViewer: false,
      urlList: [],
      fileTypeList: [],
      loading: false,
      importVisible: false,
      isBuildStatus: [],
      dataFileList: [],
      tableData: [],
      decorateTypeList: [],
      officeNature: [],
      cityLevel: [],
      businessAccount: [],
      formData: {
        dataSource: 1,
        isBuildModelRoom: 'A',
        enable: 1,
        accessory: '',
        marketLevel: '',
        submissionDate: null,
        houseDeliveryTime: null,
        submitterName: null,
        customerItem: null,
        finishedProductCustomerManagerItem: null,
        customCustomerManagerItem: null
      },
      rules: {
        communityName: [
          { required: true, message: '请输入小区名称', trigger: 'blur' },
          { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ],
        communityAddress: [
          { required: false, message: '请输入小区详细地址', trigger: 'blur' }
        ],
        houseDeliveryTime: [
          { required: true, message: '请选择交房日期', trigger: 'change' }
        ],
        roomDecorateType: [
          { required: true, message: '请选择楼盘装修类型', trigger: 'change' }
        ],
        submissionDate: [
          { required: true, message: '请选择提报月份', trigger: 'change' }
        ],
        deliveryModelRoomNumber: [
          { type: 'number', required: false, message: '请输入正确的交房户数', trigger: 'blur' }
        ],
        customerItem: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        finishedProductCustomerManagerName: [
          { required: true, message: '请选择成品客户经理', trigger: 'change' }
        ],
        customCustomerManagerItem: [
          { required: true, message: '请选择定制客户经理', trigger: 'change' }
        ],
        submitterName: [
          { required: true, message: '请选择提报人', trigger: 'change' }
        ]
      },
      signingRealEstateCustomer: '',
      clientConfig: {
        title: '客户',
        apiHeader: {
          'permission-code': 'signmng',
          'Permission-App': 'slm'
        },
        interfacePath: `/select-service/api/v1/customer/page`,
        setting: [
          {
            prop: 'code',
            title: '编码'
          },
          {
            prop: 'name',
            title: '名称'
          }
        ]
      }
    }
  },
  computed: {
    agencyNature() {
      const val = this.signingRealEstateCustomer || this.formData.agencyNature
      const item = this.officeNature.filter(item => val === item.dictCode)
      const curDictName = item[0]
      return curDictName && curDictName.dictName || null
    },
    isBuildModelRoom() {
      let curStatus = this.isBuildStatus.filter(item => item.dictCode === this.formData.isBuildModelRoom)
      curStatus = curStatus[0]
      return curStatus && curStatus.dictName || ''
    },
    marketLevel() {
      let curStatus = this.cityLevel.filter(item => item.dictCode === this.formData.marketLevel)
      curStatus = curStatus[0]
      return curStatus && curStatus.dictName || ''
    },
    readonly() {
      return this.flag === 'view'
    }
  },
  watch: { },
  async created() {
    this.getDictByPatchTypeAll()
    if (this.flag !== 'new') {
      this.loading = true
      const { data } = await signingRealEstate(null, this.row.id, 'get')
      this.patchDetail(data)
      this.loading = false
    }
  },
  methods: {
    fileView(filePath) {
      this.urlList = []
      const typeName = filePath.split('.')[1]
      const imgType = ['jpg', 'jpeg', 'png', 'gif']
      const openViewType = ['pdf', 'doc', 'docx', 'xlsx', 'xls']
      if (imgType.includes(typeName)) {
      // 图片预览
        this.showViewer = true
        const picUrl = process.env.VUE_APP_IMG_PREFIX + '/' + filePath
        this.urlList.push(picUrl)
      } else if (openViewType.includes(typeName)) {
        // word,excel预览
        window.open(`${process.env.VUE_APP_OFFICE_PREFIX}?src=` + process.env.VUE_APP_IMG_PREFIX + typeName)
      } else {
        this.$message.warning('该文件类型不支持预览')
      }
    },
    // 关闭查看器
    closeViewer() {
      this.showViewer = false
      this.urlList = []
    },
    matchFileName(path) {
      if (!path) return ''
      const pathArr = path.split('/')
      return pathArr[pathArr.length - 1]
    },
    patchDetail(data) {
      for (const key in data) {
        if (Object.hasOwnProperty.call(data, key)) {
          const item = data[key]
          this.$set(this.formData, key, item)
        }
      }
      if (data.accessory) {
        this.dataFileList = [{
          attachmentName: this.matchFileName(data.accessory),
          attachmentUrl: data.accessory,
          dr: 0
        }]
      }

      this.formData.finishedProductCustomerManagerItem = [{ name: data.finishedProductCustomerManagerName, code: data.finishedProductCustomerManagerCode }]
      this.formData.customCustomerManagerItem = [{ name: data.customCustomerManagerName, code: data.customCustomerManagerCode }]
      this.formData.customerItem = [{ name: data.customerName, code: data.customerCode }]
    },
    // 成品客户经理变更
    finishedCustomerChange(row) {
      this.$set(this.formData, 'finishedProductCustomerManagerName', row.name)
      this.$set(this.formData, 'finishedProductCustomerManagerCode', row.code)
    },
    // 定制客户经理变更
    customCustomerChange(row) {
      this.$set(this.formData, 'customCustomerManagerName', row.name)
      this.$set(this.formData, 'customCustomerManagerCode', row.code)
    },
    // 选择人员
    async getDictByPatchTypeAll() {
      const { CITY_LEVEL, DECORATION_TYPE, OFFICE_NATURE, YBJ_IS_CONSTRUCTION } =
       await getDictByPatchType(['CITY_LEVEL', 'DECORATION_TYPE', 'OFFICE_NATURE', 'YBJ_IS_CONSTRUCTION'])
      this.officeNature = OFFICE_NATURE
      this.isBuildStatus = YBJ_IS_CONSTRUCTION
      this.decorateTypeList = DECORATION_TYPE
      this.cityLevel = CITY_LEVEL
    },
    async getSigningRealEstateCustomer(code) {
      const data = await getSigningRealEstateCustomer(code)
      Object.assign(this.formData, data)
      // this.formData.agencyName = data.agencyName
      // this.formData.marketLevel = data.marketLevel
      this.signingRealEstateCustomer = data.agencyNature

      this.formData.customCustomerManagerCode = data.customCustomerManagerCode
      this.formData.customCustomerManagerName = data.customCustomerManagerName

      this.formData.finishedProductCustomerManagerCode = data.finishedProductCustomerManagerCode
      this.formData.finishedProductCustomerManagerName = data.finishedProductCustomerManagerName
    },
    chooseCons(data) {
      this.$set(this.formData, 'submitterName', data.userName)
      this.$set(this.formData, 'submitterCode', data.staffCode)
    },
    clientChoose(row) {
      this.$set(this.formData, 'finishedProductCustomerManagerItem', null)
      this.$set(this.formData, 'customCustomerManagerItem', null)
      this.formData.customerName = row[0].name
      this.formData.customerCode = row[0].code
      this.getSigningRealEstateCustomer(row[0].code)
    },
    removeFile(data) {
      this.dataFileList = []
      this.$refs.myUploader.clearUploadFile()
    },
    uploadSuccessFile(data) {
      this.dataFileList = [...data.list]
    },
    async checkForm() {
      return new Promise((resolve, reject) => {
        this.$refs.refForm.validate((valid) => {
          if (valid) {
            resolve(true)
          } else {
            resolve(false)
          }
        })
      })
    },
    goBack() {
      this.$emit('close', true)
    },
    async confirm() {
      const chkSuccess = await this.checkForm()
      if (!chkSuccess) return
      const params = {}
      const formData = this.formData
      const ignoreKey = ['taskSourceDesc', 'customerItem', 'customCustomerManagerItem', 'finishedProductCustomerManagerItem', 'submitter']
      for (const key in formData) {
        if (Object.hasOwnProperty.call(formData, key)) {
          const element = formData[key]
          if (!ignoreKey.includes(key))params[key] = element
        }
      }
      params.accessory = this.dataFileList[0] && this.dataFileList[0].attachmentUrl || ''
      this.loading = true
      // data id method
      const method = this.flag !== 'new' ? 'PUT' : 'POST'
      signingRealEstate(params, '', method).then(res => {
        this.loading = false
        if (res.success) {
          this.$message.success(this.flag !== 'new' ? '修改成功' : '创建成功')
          const timer = setTimeout(() => {
            this.goBack()
            window.clearTimeout(timer)
          }, 400)
        } else {
          this.$message.warning(res.msg)
        }
      }).catch(_ => {
        this.loading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .el-breadcrumb__inner{
    color: $qup-color-primary;
  }
/deep/.file-p {
  margin:0;
  padding:0;
  .container{
    min-height:auto;
    height:auto;
  }
}
.option-box{
    display: none;
  .option-icon{
    padding: 0 10px;
  }
}
.link-item{
  color: $--color-primary;
}
/deep/ .el-upload-list__item:first-child{
  margin-top:0;
}
 /deep/.el-autocomplete{
    width:100%;
  }
   /deep/.el-date-editor.el-input{
    width:100%;
  }
</style>
